<template>
  <el-dialog :title="title" :visible.sync="isVisible" :close-on-click-modal="false"
             width="600px" append-to-body @open="handleOpen" @close="handleClose">
    <basic-form ref="BasicForm" v-model="form" :columns="addOrEditFormConfig" label-width="120px" :col-span="24"></basic-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addCity, updateCity, getCity } from '@/api/system/city';
import { addOrEditFormConfig } from '@/views/system/city/modal.data.form';
export default {
  props: {
    isVisible: Boolean,
    title: String,
    currentId: Number,
  },
  data() {
    return {
      addOrEditFormConfig,
      form: {},
    };
  },
  methods: {
    addRequest: addCity,
    updateRequest: updateCity,
    fetchRequest: getCity,
    // 表单重置
    reset() {
      this.form.value = {
              id: null,
              city: null,
              cityGeocode: null,
              lon: null,
              lat: null,
              sort: null,
              cc: null
      };
      this.$refs.BasicForm.getForm().clearValidate();
    },
    // 取消按钮 + 关闭前处理
    handleClose() {
      this.reset();
      this.$emit('update:isVisible', false);
      this.$emit('close');
    },
    // 完成后触发列表刷新
    handleFinish() {
      this.handleClose();
      this.$emit('dialogCallBack');
    },
    // 回写表单数据
    handleFetch(id) {
      this.fetchRequest(id).then((res) => {
        this.form = res.data;
      });
    },
    // 弹窗开启
    handleOpen() {
      this.form.id = this.currentId;
      this.$nextTick(() => {
        if (this.form.id) {
          this.handleFetch(this.form.id);
          this.$refs.BasicForm.hideColumns('companyAdminPhone');
        } else {
          this.reset();
          this.$refs.BasicForm.hideColumns('companyAdminPhone');
        }
      });
    },
    // 提交按钮
    submitForm: function () {
      this.$refs.BasicForm.getForm()
              .validate((valid) => {
                if (valid) {
                  if (this.form.id) {
                    this.updateRequest({ ...this.form }).then((response) => {
                      this.$modal.msgSuccess('修改成功');
                      this.handleFinish();
                    });
                  } else {
                    this.addRequest({ ...this.form }).then((response) => {
                      this.$modal.msgSuccess('新增成功');
                      this.handleFinish();
                    });
                  }
                }
              });
    },
  },
};
</script>